package com.study.hadoop.weather;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * Reducer
 * 取每月前两条温度
 * @author stephen
 * @create 2019-01-10 21:54
 * @since 1.0.0
 */
public class WeatherReducer extends Reducer<Weather, IntWritable, Text,IntWritable> {

    Text rkey = new Text();
    IntWritable rval = new IntWritable() ;

    @Override
    protected void reduce(Weather key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        // (1950 11 12 36) 36
        // (1950 11 16 32) 32
        // (1950 11 02 31) 31
        long flag = 0;
        int day = 0 ;
        for (IntWritable v: values){
            // 随着for执行，key会跟随变化
            if(flag == 0){ // 取最高温度的天
                rkey.set(key.getYear()+"-"+key.getMonth()+":"+key.getDay());
                rval.set(v.get());
                context.write(rkey,rval);
                flag++ ;
                day = v.get();
            }

            if(flag !=0 && day != v.get()){ //  取第二高温度的天
                rkey.set(key.getYear()+"-"+key.getMonth()+":"+key.getDay());
                rval.set(v.get());
                context.write(rkey,rval);
                break;
            }
        }

    }
}
